from kazoo.client import KazooClient
from kazoo.exceptions import KazooException

zookeeper = KazooClient(hosts='47.97.221.154:2181')

try:
    # 启动会话并尝试连接
    zookeeper.start()
    
    # 检查ZooKeeper是否连接成功
    if zookeeper.client_state:
        print("Connected to ZooKeeper!")
    
except KazooException as e:
    print(f"Unable to connect to ZooKeeper: {e}")

# 对zookeeper做操组

# 1、创建一个Znode
try:
    zookeeper.create('/python-zNode-test-01',b'Some undisclosed secrets')
    print("Created znode '/python-znode-test' with data Successful")
except KazooException as e:
    print(f"Failed to create znode: {e}")

# 2、读取znode数据
try:
    data, _ = zookeeper.get('/')
    print(f"Data from znode : {data}")
except KazooException as e:
    print(f"Failed to get znode data: {e}")
# 2.1、查看所有的节点
try:
    nodes = zookeeper.get_children('/')
    print("ZooKeeper nodes:", nodes)
except Exception as e:
    print("An error occurred:", e)

# 3、更新znode数据
try:
    zookeeper.set('/python-zNode-test-01', b'maybe call you,but you son of bitch')
    print("Updated znode data Successful")
except KazooException as e:
    print(f"Failed to update znode data: {e}")
# 4、删除znode
try:
    zookeeper.delete('/brokers',recursive=True)
    print("Deleted znode '/brokers' Successful")
except KazooException as e:
    print(f"Failed to delete znode: {e}")

zookeeper.stop()